// pages/register/register.js
const App = getApp()
import {
    setStore,
    getStore
} from '../../utils/storage'

import {
    login
} from '../../api/user/user'
import mode from '../../utils/mode'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        scoreOk:false,
        temIds:['sFvDqiPjsACPW16U6q1Qz6Y5-Gh-ahwAqSDVy4H6laI','ozvgibebCwysJJcuL0_qN26GWySVilWU2yCJOwqkumA','Wzq0Q8OpleP_KgHNxStTKJ6-8NdvRvqgJnioZ01w7bg'],
        dingYueOK:1,
        isCoupon:'',   //是否是优惠券页面过来
        isBind: false,


        share_id: '',
        lastUrl: '',   //登录前要去的路径

        showPhone: '',
        showSuccess: false,
        member_score: '',
        error: false,
        show: false,
        realityPhone: '',
        form: {
            nickname: '',
            phone: ''
        },
        checked: false,
        id: '',
        fromUrl: '',
        isFrom: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let ctx = getCurrentPages()
        this.setData({
            fromUrl: ctx[0] ? ctx[0].route : '',
            isFrom: wx.getStorageSync('isFrom') || '',
            isCoupon:options.isCoupon?1:0
        })
        var uinfo = wx.getStorageSync('uinfo') || null
        let lastUrl = wx.getStorageSync('lastUrl')
        if (lastUrl) {
            this.setData({
                lastUrl: lastUrl,
            })
        }
        wx.setStorage({
            key: "is_member",
            data: "0"
        })
        var share_id = wx.getStorageSync('share_id') || ''
        this.setData({
            share_id: share_id
        })
        var that = this
        if (!uinfo||!uinfo.user||!uinfo.user.id) {
            wx.showModal({
                title: '提示',
                content: '2AM早寻是会员专属空间，一键授权完成注册，即可顺畅使用。',
                success: function (res) {
                    if (res.confirm) {
                        that.handleClickOpenLogiaDialog()
                    } else {
                        setTimeout(() => {
                            let { fromUrl, isFrom } = that.data
                            if (fromUrl && fromUrl == 'pages/user/user' && isFrom) {
                                wx.switchTab({ url: isFrom })
                            } else {
                                App.backPage()
                            }
                        }, 300)
                    }
                }
            })
        } else {
            this.setData({
                'form.nickname': uinfo.user.user_nickname,
                id: uinfo.user.id
            })
            if (lastUrl&&lastUrl=='/pages/questionnaire/questionnaire') {
                wx.showModal({
                    title: '',
                    content: '肤质测试前请绑定会员',
                    confirmText: '立即绑定',
                    cancelText: '稍后测试',
                    success: function (res) {
                        if (res.confirm) {
                        } else {
                            App.backPage()
                        }
                    }
                })
            }
        }
    },
    onClose(){
        let that = this
        this.setData({
            showSuccess:false
        })
        if (that.data.lastUrl) {
            wx.setStorage({
                data: '',
                key: 'lastUrl',
            })
            if(that.data.lastUrl=='/pages/exclusive/exclusive'){
                wx.switchTab({
                    url: '/pages/exclusive/exclusive',
                  })
            }else{
                wx.redirectTo({
                    url: that.data.lastUrl,
                })
            }
        } else {
            wx.redirectTo({
                url: '/pages/info/info?isRegister=' + '1',
            })
        }
    },
    handleClickOpenLogiaDialog () {    //微信授权登录
        var that = this
        var shareId = wx.getStorageSync('share_id') || that.data.share_id
        wx.getUserProfile({
            desc: '用于完善会员资料',
            success: (res) => {
                App.globalData.userinfo = res
                wx.setStorageSync('vip_name', res.userInfo.nickName)
                const {
                    iv,
                    rawData,
                    signature,
                    encryptedData
                } = App.globalData.userinfo
                const data = {
                    code: App.globalData.code,
                    encrypted_data: encryptedData,
                    iv: iv,
                    raw_data: rawData,
                    signature: signature,
                    share_id: shareId||''
                }
                login(data).then(res => {
                    if(res.code==1&&res.data.user&&res.data.user.id){
                        const {
                            wxUserData
                        } = res.data
                        wx.setStorage({ key: "uinfo", data: res.data })
                        if (that.data.share_id) {    //被分享
                            wx.removeStorage({
                                key: 'share_id'
                            })
                        }
                        setStore('share_id', '')
                        setStore('wxUserData', wxUserData)
                        that.setData({
                            'form.nickname': res.data.user.user_nickname,
                            id: res.data.user.id
                        })
                        if(that.data.isCoupon){
                            App.backPage()
                        }else if (res.data.user.is_member && res.data.user.is_member == 1) {  //已注册会员
                            if (that.data.lastUrl) {
                                wx.setStorage({
                                    data: '',
                                    key: 'lastUrl',
                                })
                                if(that.data.lastUrl=='/pages/exclusive/exclusive'){
                                    wx.switchTab({
                                        url: '/pages/exclusive/exclusive',
                                      })
                                }else{
                                    wx.redirectTo({
                                        url: that.data.lastUrl,
                                    })
                                }
                            } else {
                                App.backPage()
                            }
                        } else {
                            if (that.data.lastUrl&&that.data.lastUrl=='/pages/questionnaire/questionnaire') {
                                wx.showModal({
                                    title: '',
                                    content: '肤质测试前请绑定会员',
                                    confirmText: '立即绑定',
                                    cancelText: '稍后测试',
                                    success: function (res) {
                                        if (res.confirm) {
    
                                        } else {
                                            App.backPage()
                                        }
                                    }
                                })
                            }
                        }
                    }else{
                        wx.removeStorage({
                            key: 'uinfo'
                        })
                        wx.showToast({
                          title: '登录失败',
                          icon:"error"
                        })
                        setTimeout(() => {
                            wx.switchTab({
                              url: '/pages/index/index',
                            })
                        }, 1500);
                    }
                    
                })
            },
            fail () {
                setTimeout(() => {
                    let { fromUrl, isFrom } = that.data
                    if (fromUrl && fromUrl == 'pages/user/user' && isFrom) {
                        wx.switchTab({ url: isFrom })
                    } else {
                        App.backPage()
                    }
                }, 300)
            }

        })
    },
    onCheckedChange (event) {
        this.setData({
            checked: event.detail,
        })
        // if(event.detail&&this.data.dingYueOK==1){
        //     this.setInfo()
        // }
    },
    onPhoneChange (e) {
        this.setData({
            'form.phone': e.detail
        })
    },
    onNicknameChange (e) {
        this.setData({
            'form.nickname': e.detail
        })
    },
    handleClickConfirm () {
        wx.redirectTo({
            url: '../info/info',
            success: () => {
                this.show = false
            }
        })
    },
    handleClickSubmit () {
        if (this.data.isBind == true) return
        this.setData({
            isBind: true
        })
        var that = this
        var formData = that.isFormEmpty()
        if (!formData) {
            wx.showModal({
                title: '温馨提示',
                content: '请将信息填写完整',
                showCancel: false,
                success (res) { }
            })
            that.setData({
                error: true,
                isBind: false
            })

        } else if (!that.data.checked) {
            wx.showModal({
                title: '温馨提示',
                content: '未勾选2AM使用条款和条件',
                showCancel: false,
                success (res) { }
            })
            that.setData({
                isBind: false
            })
        } else {
            let phoneIndex = String(that.data.form.phone).indexOf('*')
            let phone = phoneIndex == -1 ? that.data.form.phone : that.data.realityPhone
            wx.$api.setLoginUser({
                    user_id: that.data.id,
                    mobile: phone
                }).then(resok=>{
                    if (resok.code) {
                        that.beOk()
                    } else {
                        wx.showToast({
                            title: '注册会员失败',
                            icon: 'error',
                            duration: 2000
                        })
                        that.setData({
                            isBind: false
                        })
                    }
            })
        }
    },

    isFormEmpty () {
        const {
            form
        } = this.data
        console.log(form)
        return Object.keys(form).every(key => form[key] !== '')
    },

    getPhoneNumber (e) {
        var that = this
        console.log(e);
        if(e.detail.errMsg == 'getPhoneNumber:fail user deny'){
            App.backPage()
            return
        }
        if(e.detail.code){  //新版本
            let logData = {
                code:e.detail.code,
            }
            that.getPhone(logData)
        }else{//微信基础库版本为旧版本
            wx.login({
                success:res=>{
                    let logData = {
                        code:res.code,
                        iv:e.detail.iv,
                        encryptedData:e.detail.encryptedData,
                    }
                    that.getPhone(logData)
                }
            })
        }
    },
    getPhone(data){
        let that = this
        wx.$api.getWechatUserPhoneV2(data).then(res=>{
                if(res.code==1){
                    let number = res.msg.phone_info.phoneNumber
                    let num1 = number.substr(0, 3)
                    let num2 = number.substr(7, 4)
                    that.setData({
                        showPhone: num1 + '****' + num2,
                        'form.phone': number
                    })
                    var userInfo = wx.getStorageSync('uinfo')
                    mode.getUserInfo(that.data.id).then(item => {
                        if (item &&item.code==1&& item.data&& item.data.id) {
                            userInfo.user = item.data
                            wx.setStorage({ key: "uinfo", data: userInfo })
                        }else{
                            wx.showToast({
                                title: '获取用户信息失败！',
                                icon:'none'
                              })
                        }
                    })
                }else{
                    wx.showToast({
                      title: '获取手机号失败！',
                      icon:'none'
                    })
                }
        })
    },
    setInfo(){   //提示订阅消息
        let that = this
        wx.requestSubscribeMessage({
            tmplIds: that.data.temIds,
            success (res) {
                console.log(res);
                that.setData({
                    dingYueOK:2
                })
                
                if(res[that.data.temIds[0]]=='reject'){//拒绝
                    that.setData({
                        dingYueOK:0
                    })
                }else{  //允许
                    that.setData({
                        dingYueOK:2
                    })
                    if(res[that.data.temIds[1]]=='reject'){
                        that.setData({
                            scoreOk:false
                        })
                    }else{
                        that.setData({
                            scoreOk:true
                        })
                    }
                }
            },
            fail(error){
                that.setData({
                    dingYueOK:0
                })
            }
          })
    },
    sendSetYue(){
        let that = this
        let allData={}
        if(that.data.scoreOk){
            allData={
                user_id: that.data.id,
                type:'1,3',
                other_type:1
            }
        }else{
            allData={
                user_id: that.data.id,
                type:'1'
            }
        }
        wx.$api.sendTemplate(allData).then(res=>{
                if(res.code>0){
                    
                }else{
                    wx.showToast({
                      title: res.msg,
                      icon:'none'
                    })
                }
        })
    },
    hidePhoneNum (phone) {
        let result = ""
        if (phone != null) {
            result = phone.substring(0, 3) + "****" + phone.substring(7)
        }
        return result
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let that = this
        var uinfo = wx.getStorageSync('uinfo')
        if (uinfo && uinfo.user.is_member == 1) {
            if (that.data.lastUrl) {
                wx.removeStorage({
                    key: 'lastUrl',
                })
                if(that.data.lastUrl=='/pages/exclusive/exclusive'){
                    wx.switchTab({
                        url: '/pages/exclusive/exclusive',
                      })
                }else{
                    wx.redirectTo({
                        url: that.data.lastUrl,
                    })
                }
            } else {
                App.backPage()
                // wx.redirectTo({
                //     url: '/pages/info/info?isRegister=' + '1',
                // })
            }
        }
        this.getScoreSet()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        wx.removeStorage({
            key: 'lastUrl',
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    toTiaoKuan (e) {
        wx.redirectTo({
            url: '../police/police',
        })

    },
    format (time, format) {
        var t = new Date(time)
        var tf = function (i) {
            return (i < 10 ? '0' : '') + i
        }
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
            switch (a) {
                case 'yyyy':
                    return tf(t.getFullYear())
                    break
                case 'MM':
                    return tf(t.getMonth() + 1)
                    break
                case 'mm':
                    return tf(t.getMinutes())
                    break
                case 'dd':
                    return tf(t.getDate())
                    break
                case 'HH':
                    return tf(t.getHours())
                    break
                case 'ss':
                    return tf(t.getSeconds())
                    break
            }
        })
    },
    randomString: function (n) {
        let str = 'abcdefghijklmnopqrstuvwxyz9876543210'
        let tmp = '',
            i = 0,
            l = str.length
        for (i = 0; i < n; i++) {
            tmp += str.charAt(Math.floor(Math.random() * l))
        }
        return tmp
    },
    getScoreSet () {
        var that = this
        wx.$api.getScoreSet().then(res=>{
                that.setData({
                    member_score: res.data.register
                })
        })
    },
    beOk () {
        var that = this
        var userInfo = wx.getStorageSync('uinfo')
        mode.getUserInfo(that.data.id).then(item => {
            if (item &&item.code==1&& item.data&& item.data.id) {
                userInfo.user = item.data
                wx.setStorage({ key: "uinfo", data: userInfo })
            }
            that.setData({
                showSuccess: true,
                isBind: false
            })
        })
    },
    goInfo () {
        this.setData({
            showSuccess: false
        })
        const url = 'https://mp.weixin.qq.com/s/OVwXNiS_A0AERMrJBd9wjA'; // 跳转的地止,这里写你想要跳转的公众号地止即可
        const navtitle = '2AM早寻公众号'; // 小程序跳转到公众号页面显示的标题
        wx.navigateTo({
        // 跳转到webview页面
        url: `/pages/webview/webview?url=${url}&nav=${navtitle}`,
        });

    }
})